<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="width=device-width, initial-scale=1">
        <meta name="robots" content="noodp" />
        <meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1">
        <title>《Flutter引擎奔溃分析方法简介》 - 飞雪无情的博客</title><meta name="Description" content="专注于IT互联网，包括但不限于Go语言(golang)、Java、Android、Python、项目管理、抖音分析、软件架构等"><meta property="og:title" content="《Flutter引擎奔溃分析方法简介》" />
<meta property="og:description" content="
本文主要介绍
" />
<meta property="og:type" content="article" />
<meta property="og:url" content="https://www.flysnow.org/posts/flutter/Flutter%E5%BC%95%E6%93%8E%E5%A5%94%E6%BA%83%E5%88%86%E6%9E%90%E6%96%B9%E6%B3%95%E7%AE%80%E4%BB%8B/" />
<meta property="article:published_time" content="2021-07-31T18:33:42+08:00" />
<meta property="article:modified_time" content="2021-07-31T18:33:42+08:00" />
<meta name="twitter:card" content="summary"/>
<meta name="twitter:title" content="《Flutter引擎奔溃分析方法简介》"/>
<meta name="twitter:description" content="
本文主要介绍
"/>
<meta name="application-name" content="飞雪无情的博客">
<meta name="apple-mobile-web-app-title" content="飞雪无情的博客"><link rel="shortcut icon" type="image/x-icon" href="/favicon.ico" />
        <link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
        <link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png"><link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png"><link rel="manifest" href="/site.webmanifest"><link rel="canonical" href="https://www.flysnow.org/posts/flutter/Flutter%E5%BC%95%E6%93%8E%E5%A5%94%E6%BA%83%E5%88%86%E6%9E%90%E6%96%B9%E6%B3%95%E7%AE%80%E4%BB%8B/" /><link rel="prev" href="https://www.flysnow.org/posts/flutter/flutter%E6%98%AF%E5%A6%82%E4%BD%95%E5%B7%A5%E4%BD%9C%E7%9A%84/" /><link rel="next" href="https://www.flysnow.org/posts/flutter/Dart%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E4%B9%8BStream/" /><link rel="stylesheet" href="/lib/normalize/normalize.min.css"><link rel="stylesheet" href="/css/style.min.css"><link rel="stylesheet" href="/lib/fontawesome-free/all.min.css"><link rel="stylesheet" href="/lib/animate/animate.min.css"><script type="application/ld+json">
    {
        "@context": "http://schema.org",
        "@type": "BlogPosting",
        "headline": "《Flutter引擎奔溃分析方法简介》",
        "inLanguage": "zh-CN",
        "mainEntityOfPage": {
            "@type": "WebPage",
            "@id": "https:\/\/www.flysnow.org\/posts\/flutter\/Flutter%E5%BC%95%E6%93%8E%E5%A5%94%E6%BA%83%E5%88%86%E6%9E%90%E6%96%B9%E6%B3%95%E7%AE%80%E4%BB%8B\/"
        },"genre": "posts","keywords": "flutter","wordcount":  1095 ,
        "url": "https:\/\/www.flysnow.org\/posts\/flutter\/Flutter%E5%BC%95%E6%93%8E%E5%A5%94%E6%BA%83%E5%88%86%E6%9E%90%E6%96%B9%E6%B3%95%E7%AE%80%E4%BB%8B\/","datePublished": "2021-07-31T18:33:42+08:00","dateModified": "2021-07-31T18:33:42+08:00","publisher": {
            "@type": "Organization",
            "name": "飞雪无情"},"author": {
                "@type": "Person",
                "name": "飞雪无情"
            },"description": ""
    }
    </script></head>
    <body header-desktop="" header-mobile=""><script type="text/javascript">(window.localStorage && localStorage.getItem('theme') ? localStorage.getItem('theme') === 'dark' : ('' === 'auto' ? window.matchMedia('(prefers-color-scheme: dark)').matches : '' === 'dark')) && document.body.setAttribute('theme', 'dark');</script>

        <div id="mask"></div><div class="wrapper"><div class="logo-wrapper">
  <a href="/%20/" class="logo">飞雪无情的博客</a>
</div>

<nav class="site-navbar">
  <ul id="menu" class="menu">
    <li class="menu-item">
      <a class="menu-item-link" href="/tools/">工具</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/archives/">归档</a>
    </li><li class="menu-item">
      <a class="menu-item-link" href="/about/">关于</a>
    </li>
  </ul>
</nav><main class="main">
                <div class="container"><div class="toc" id="toc-auto">
            <h2 class="toc-title">Contents</h2>
            <div class="toc-content" id="toc-content-auto"></div>
        </div><article class="page single"><h1 class="single-title animated flipInX">《Flutter引擎奔溃分析方法简介》</h1><div class="post-meta">
            <div class="post-meta-line"><span class="post-author"><a href="/" title="Author" rel=" author" class="author"><i class="fas fa-user-circle fa-fw"></i>飞雪无情</a></span>&nbsp;<span class="post-category">included in <a href="/categories/Flutter/"><i class="far fa-folder fa-fw"></i>Flutter</a></span></div>
            <div class="post-meta-line"><i class="far fa-calendar-alt fa-fw"></i>&nbsp;<time datetime="2021-07-31">2021-07-31</time>&nbsp;<i class="fas fa-pencil-alt fa-fw"></i>&nbsp;1095 words&nbsp;
                <i class="far fa-clock fa-fw"></i>&nbsp;3 minutes&nbsp;</div>
        </div><div class="featured-image"><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        data-srcset="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 1.5x, https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png 2x"
        data-sizes="auto"
        alt="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png"
        title="https://luckly007.oss-cn-beijing.aliyuncs.com/img/90c6cc12-742e-4c9f-b318-b912f163b8d0.png" /></div><div class="details toc" id="toc-static"  kept="">
                <div class="details-summary toc-title">
                    <span>Contents</span>
                    <span><i class="details-icon fas fa-angle-right"></i></span>
                </div>
                <div class="details-content toc-content" id="toc-content-static"><nav id="TableOfContents"></nav></div>
            </div><div class="content" id="content"><blockquote>
<p>本文主要介绍</p>
</blockquote>
<p>Android 项目信息 Flutter 后上线，偶尔会遇到一些 Flutter 引擎的崩溃。简单记录下如何还原引擎崩溃日志，方便在源码中定位问题。</p>
<h1 id="flutter-engine-crash-堆栈还原">Flutter Engine Crash 堆栈还原</h1>
<p>首先，在 <code>bin/internal/engine.version</code> 找到 flutter engine revision</p>
<pre><code>b851c718295a896918dc93cb1ff14f2f895a1b90
</code></pre><p>第二步，下载带符号表的 <code>libflutter.so</code> 文件</p>
<pre><code>https://console.cloud.google.com/storage/browser/flutter_infra/flutter/b851c718295a896918dc93cb1ff14f2f895a1b90
</code></pre><p>第三步，利用 <code>ndk-stack</code> 还原堆栈信息</p>
<pre><code>/path/to/android-ndk-r16b/ndk-stack -sym /path/to/symbols/armeabi-v7a -dump /path/to/stacktrace.txt
</code></pre><p>如果是将 crash 上报到 bugly 平台，则不必使用 <code>ndk-stack</code>，直接在 bugly 上配置符号表即可。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938295883428.jpg"
        data-srcset="https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938295883428.jpg, https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938295883428.jpg 1.5x, https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938295883428.jpg 2x"
        data-sizes="auto"
        alt="https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938295883428.jpg"
        title="img" /></p>
<p>配置成功后就能在 bugly 平台上看到 native crash 堆栈信息。</p>
<p>原始堆栈信息
<img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938297243231.jpg"
        data-srcset="https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938297243231.jpg, https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938297243231.jpg 1.5x, https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938297243231.jpg 2x"
        data-sizes="auto"
        alt="https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938297243231.jpg"
        title="img" /></p>
<p>还原后的堆栈信息
<img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938297398367.jpg"
        data-srcset="https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938297398367.jpg, https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938297398367.jpg 1.5x, https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938297398367.jpg 2x"
        data-sizes="auto"
        alt="https://blog-1251688504.cos.ap-shanghai.myqcloud.com/2020/07/04/15938297398367.jpg"
        title="img" /></p>
<p>拿到还原后的堆栈信息，就可以对着源码分析问题了。</p>
<h1 id="一个疑问">一个疑问</h1>
<p>官方提到每个 <code>libflutter.so</code> 文件中有一个 build id，native crash 堆栈中见到的 <code>BuildId</code> 要跟 <code>libflutter.so</code> 的匹配，否则没法还原 native crash 堆栈信息。原文如下：</p>
<blockquote>
<p>The build system sets a build id for each libflutter.so file. In the tombstones, you would see the ID like so:</p>
</blockquote>
<blockquote>
<pre><code>&gt; #00 pc 000000000062d6e0  /data/app/com.app-tARy3eLH2Y-QN8J0d0WFog==/lib/arm64/libflutter.so!libflutter.so (offset 0x270000) (BuildId: 34ad5bdf0830d77a)
&gt;
</code></pre></blockquote>
<blockquote>
<p>This equals to a build id of 34ad5bdf0830d77a. The libflutter.so debug files downloaded as shown above could be verified using the file command:</p>
</blockquote>
<blockquote>
<pre><code>&gt; % file ~/Downloads/libflutter.so
&gt; /Users/user/Downloads/libflutter.so: ELF 64-bit LSB shared object, ARM aarch64, version 1 (SYSV), dynamically linked, BuildID[xxHash]=34ad5bdf0830d77a, with debug_info, not stripped
&gt;
</code></pre></blockquote>
<blockquote>
<p>Ensure the build IDs match, else you will not be able to symbolicate.</p>
</blockquote>
<p>不过我往 bugly 上传了一个非严格匹配的符号表(上报 crash 的 app 使用的是自己编译的 <code>libflutter.so</code>，符号表是官方提供的 <code>libflutter.so</code>)，也能还原出来。让人很是疑惑。</p>
<p>观察了下，bugly 上看到的 native crash 日志中并没有找到类似 <code>(BuildId: 34ad5bdf0830d77a)</code> 这样的信息。<em>推测</em>由此导致匹配变得不严格，所以也能还原出来。</p>
<h1 id="实例">实例</h1>
<p>某个 native crash 还原后得到如下堆栈信息。</p>
<p><img
        class="lazyload"
        src="/svg/loading.min.svg"
        data-src="https://www.sunmoonblog.com/images/15938315565456.jpg"
        data-srcset="https://www.sunmoonblog.com/images/15938315565456.jpg, https://www.sunmoonblog.com/images/15938315565456.jpg 1.5x, https://www.sunmoonblog.com/images/15938315565456.jpg 2x"
        data-sizes="auto"
        alt="https://www.sunmoonblog.com/images/15938315565456.jpg"
        title="img" /></p>
<p>首先看到的是 <code>message_loop_impl.cc</code> 中的 <code>MessageLoopImpl::RunExpiredTasksNow</code>。这个方法会立即执行任务队列中的已过期任务。</p>
<pre><code>void MessageLoopImpl::FlushTasks(FlushType type) {
  TRACE_EVENT0(&quot;fml&quot;, &quot;MessageLoop::FlushTasks&quot;);
  std::vector&lt;fml::closure&gt; invocations;

  task_queue_-&gt;GetTasksToRunNow(queue_id_, type, invocations);

  for (const auto&amp; invocation : invocations) {
    invocation();
    std::vector&lt;fml::closure&gt; observers =
        task_queue_-&gt;GetObserversToNotify(queue_id_);
    for (const auto&amp; observer : observers) {
      observer();
    }
  }
}

void MessageLoopImpl::RunExpiredTasksNow() {
  FlushTasks(FlushType::kAll);
}
</code></pre><p>接下来看到的是 <code>platform_view_android_jni.cc</code> 中的 <code>FlutterViewUpdateSemantics</code></p>
<pre><code>void FlutterViewUpdateSemantics(JNIEnv* env,
                                jobject obj,
                                jobject buffer,
                                jobjectArray strings) {
  // 调用 g_update_semantics_method (Java 层方法)
  env-&gt;CallVoidMethod(obj, g_update_semantics_method, buffer, strings);
  // 检查 Java 代码是否发生异常，有异常则写入 fml 日志中
  FML_CHECK(CheckException(env));
}

bool RegisterApi(JNIEnv* env) {
  // g_update_semantics_method 对应的是 
  // Java 层中的 FlutterJNI.updateSemantics() 方法
  g_update_semantics_method =
      env-&gt;GetMethodID(g_flutter_jni_class-&gt;obj(), &quot;updateSemantics&quot;,
                       &quot;(Ljava/nio/ByteBuffer;[Ljava/lang/String;)V&quot;);
  ...
  return true;
}

// 检查 Java 代码是否发生异常
// 发生异常时返回 false，否则返回 true
bool CheckException(JNIEnv* env) {
  if (env-&gt;ExceptionCheck() == JNI_FALSE)
    return true;

  jthrowable exception = env-&gt;ExceptionOccurred();
  env-&gt;ExceptionClear();
  FML_LOG(ERROR) &lt;&lt; fml::jni::GetJavaExceptionInfo(env, exception);
  env-&gt;DeleteLocalRef(exception);
  return false;
}
</code></pre><p>最后看到的是 <code>logging.cc</code> 第92行。</p>
<pre><code>LogMessage::~LogMessage() {
  stream_ &lt;&lt; std::endl;

#if defined(OS_ANDROID)
  android_LogPriority priority =
      (severity_ &lt; 0) ? ANDROID_LOG_VERBOSE : ANDROID_LOG_UNKNOWN;
  switch (severity_) {
    case LOG_INFO:
      priority = ANDROID_LOG_INFO;
      break;
    case LOG_WARNING:
      priority = ANDROID_LOG_WARN;
      break;
    case LOG_ERROR:
      priority = ANDROID_LOG_ERROR;
      break;
    case LOG_FATAL:
      priority = ANDROID_LOG_FATAL;
      break;
  }
  __android_log_write(priority, &quot;flutter&quot;, stream_.str().c_str());
#elif defined(OS_IOS)
  syslog(LOG_ALERT, &quot;%s&quot;, stream_.str().c_str());
#else
  std::cerr &lt;&lt; stream_.str();
  std::cerr.flush();
#endif

  if (severity_ &gt;= LOG_FATAL) {
    // 最终的 crash 由这里产生
    abort();
  }
}
</code></pre><p>初看起来可能会有点不明白 crash 如何产生，梳理一下就渐渐明了：</p>
<ul>
<li>调用 <code>RunExpiredTasksNow</code> 立即执行队伍中的过期任务</li>
<li>过期任务中的某一个任务调用了 <code>FlutterViewUpdateSemantics()</code> (C++层)</li>
<li><code>FlutterViewUpdateSemantics()</code> 调用 <code>FlutterJNI.updateSemantics()</code> (Java层)</li>
<li><code>FlutterViewUpdateSemantics()</code> 调用 <code>CheckException()</code> 检查 Java 代码执行后是否产生异常</li>
<li><code>FlutterViewUpdateSemantics()</code> 调用 <code>FML_CHECK()</code> 记录错误日志 (如有 Java 异常)</li>
</ul>
<p>所以我们可以把怀疑目标锁定到 <code>FlutterJNI.updateSemantics()</code> 方法。剩下的工作就是进入 Java 层分析该方法的出错原因了。</p>
<pre><code>@Keep
public class FlutterJNI {
  ...
  
  /**
   * Invoked by native to send semantics tree updates from Flutter to Android.
   *
   * The {@code buffer} and {@code strings} form a communication protocol that is implemented here:
   * https://github.com/flutter/engine/blob/master/shell/platform/android/platform_view_android.cc#L207
   */
  @SuppressWarnings(&quot;unused&quot;)
  @UiThread
  private void updateSemantics(@NonNull ByteBuffer buffer, @NonNull String[] strings) {
    ensureRunningOnMainThread();
    if (accessibilityDelegate != null) {
      accessibilityDelegate.updateSemantics(buffer, strings);
    }
    // TODO(mattcarroll): log dropped messages when in debug mode (https://github.com/flutter/flutter/issues/25391)
  }
  
  ...
}
</code></pre><h1 id="参考">参考</h1>
<ul>
<li><a href="https://fucknmb.com/2019/10/20/%e8%8e%b7%e5%8f%96%e5%b9%b6%e8%bf%98%e5%8e%9fFlutter-Engine-Crash%e5%a0%86%e6%a0%88/" target="_blank" rel="noopener noreffer">获取并还原 Flutter Engine Crash 堆栈 | 区长</a></li>
<li><a href="https://github.com/flutter/flutter/wiki/Crashes" target="_blank" rel="noopener noreffer">Crashes · flutter/flutter Wiki</a></li>
</ul></div><div class="post-footer" id="post-footer">
    <div class="post-info">
        <div class="post-info-line">
            <div class="post-info-mod">
                <span>Updated on 2021-07-31</span>
            </div>
            <div class="post-info-license"></div>
        </div>
        <div class="post-info-line">
            <div class="post-info-md"></div>
            <div class="post-info-share">
                <span></span>
            </div>
        </div>
    </div>

    <div class="post-info-more">
        <section class="post-tags"><i class="fas fa-tags fa-fw"></i>&nbsp;<a href="/tags/flutter/">flutter</a></section>
        <section>
            <span><a href="javascript:void(0);" onclick="window.history.back();">Back</a></span>&nbsp;|&nbsp;<span><a href="/">Home</a></span>
        </section>
    </div>

    <div class="post-nav"><a href="/posts/flutter/flutter%E6%98%AF%E5%A6%82%E4%BD%95%E5%B7%A5%E4%BD%9C%E7%9A%84/" class="prev" rel="prev" title="《Flutter是如何工作的》"><i class="fas fa-angle-left fa-fw"></i>《Flutter是如何工作的》</a>
            <a href="/posts/flutter/Dart%E5%BC%82%E6%AD%A5%E7%BC%96%E7%A8%8B%E4%B9%8BStream/" class="next" rel="next" title="《Dart异步编程之Stream》">《Dart异步编程之Stream》<i class="fas fa-angle-right fa-fw"></i></a></div>
</div>
</article></div>
            </main><footer class="footer">
        <div class="footer-container"><div class="footer-line">Powered by <a href="https://gohugo.io/" target="_blank" rel="noopener noreffer" title="Hugo 0.79.1">Hugo</a> | Theme - <a href="https://github.com/dillonzq/LoveIt" target="_blank" rel="noopener noreffer" title="LoveIt 0.2.10"><i class="far fa-kiss-wink-heart fa-fw"></i> LoveIt</a>
                </div><div class="footer-line"><i class="far fa-copyright fa-fw"></i><span itemprop="copyrightYear">2021</span><span class="author" itemprop="copyrightHolder">&nbsp;<a href="/" target="_blank">飞雪无情</a></span></div>
        </div>
    </footer></div>

        <div id="fixed-buttons"><a href="#" id="back-to-top" class="fixed-button" title="Back to Top">
                <i class="fas fa-arrow-up fa-fw"></i>
            </a><a href="#" id="view-comments" class="fixed-button" title="View Comments">
                <i class="fas fa-comment fa-fw"></i>
            </a>
        </div><script type="text/javascript" src="/lib/smooth-scroll/smooth-scroll.min.js"></script><script type="text/javascript" src="/lib/lazysizes/lazysizes.min.js"></script><script type="text/javascript" src="/lib/clipboard/clipboard.min.js"></script><script type="text/javascript" src="/lib/sharer/sharer.min.js"></script><script type="text/javascript">window.config={"code":{"copyTitle":"Copy to clipboard","maxShownLines":10},"comment":{}};</script><script type="text/javascript" src="/js/theme.min.js"></script></body>
</html>
